﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using EfSample.Model;

namespace EfSampel.WebApp.Controllers
{
    public class ModelController<TEntity> : Controller
        where TEntity : class , IEntity
    {
        public IRepository<TEntity> ModelRepository { get; set; }

        public ActionResult Index()
        {
            var models = ModelRepository.FindAll().ToList();
            return View(models);
        }

        public ActionResult Create()
        {
            return View("Edit");
        }

        [HttpPost]
        public ActionResult Create(TEntity entity)
        {
            try
            {
                using (var scope = new TransactionScope())
                {
                    ModelRepository.Add(entity);
                    scope.Complete();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            using (var scope = new TransactionScope())
            {
                var entity = ModelRepository.FindById(id);
                ModelRepository.Delete(entity);
                scope.Complete();
            }
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            var entity = ModelRepository.FindById(id);
            return View(entity);
        }

        [HttpPost]
        public ActionResult Edit(TEntity entity)
        {
            try
            {
                using (var scope = new TransactionScope())
                {
                    ModelRepository.Update(entity);
                    scope.Complete();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
